package com.learn.demo.controller;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.UUID;

import com.learn.demo.entity.User;
import com.learn.demo.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/test")
public class UserController {
	@Autowired
	private UserService userService;

	/**
	 * 得到数据库中所有数据
	 * @return
	 */
	@ResponseBody
	@GetMapping("/getAllUsers")
	public ArrayList<User> getAllUsers(){
		//添加一个固定的User，并且设定User的userName、passWord为本机IP、本机名称
		ArrayList<User> users=userService.getUsers();
		InetAddress addr = null;
		try {
			addr = InetAddress.getLocalHost();
			String ip=addr.getHostAddress();//获得本机IP
			String address=addr.getHostName();//获得本机名称
			User u=new User();
			u.setUsername(ip);
			u.setPassword(address);
			users.add(u);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			User u=new User();
			u.setUsername("exception");
			u.setPassword("exception");
			users.add(u);
		}

		return users;
	}

	/**
	 * 添加用户
	 * @return
	 */
	@ResponseBody
	@GetMapping("/addUser")
	public String  addUser(){
		User user=new User();
		user.setUsername(UUID.randomUUID().toString().replaceAll("-",""));
		user.setPassword(UUID.randomUUID().toString().replaceAll("-",""));
		userService.addUser(user);
		InetAddress addr = null;
		try {
			addr = InetAddress.getLocalHost();
			String ip=addr.getHostAddress();//获得本机IP
			String address=addr.getHostName();//获得本机名称
			return "添加成功"+" docker ip："+ip+" docker address："+address;
		}catch (UnknownHostException e) {
			e.printStackTrace();
		}

		return "添加成功 exception";
	}

}
